<template>
  <el-dialog
    v-model="visible"
    :title="dialogTitle"
    width="1000px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :destroy-on-close="true"
    class="dlg-fixed-footer"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="108px">
      <!-- 设备 -->
      <el-form-item label="设备名称">
        <el-input :model-value="assetName" disabled />
      </el-form-item>

      <!-- 通用字段 -->
      <el-form-item label="计划标题" prop="title">
        <el-input
          v-model="form.title"
          maxlength="80"
          show-word-limit
          placeholder="请输入计划标题"
        />
      </el-form-item>

      <el-form-item label="计划日期" prop="planDate">
        <el-date-picker
          v-model="form.planDate"
          type="date"
          value-format="YYYY-MM-DD"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="计划工时" prop="planHour">
        <el-input-number
          v-model="form.planHour"
          maxlength="80"
          show-word-limit
          placeholder="单位(时)"
        />
      </el-form-item>

      <el-form-item label="计划状态" prop="status">
        <el-select
          v-model="form.status"
          placeholder="选择状态"
          style="width: 100%"
        >
          <el-option label="待执行" value="OPEN" />
          <el-option label="已取消" value="CANCELLED" />
          <el-option label="已完成" value="DONE" />
        </el-select>
      </el-form-item>

      <el-form-item label="维护工种">
        <el-input
          v-model="form.tradeCode"
          maxlength="80"
          show-word-limit
          placeholder="请输入维护工种"
        />
      </el-form-item>

      <el-form-item label="计划内容" class="span-2">
        <el-input
          v-model="form.planContent"
          type="textarea"
          rows="3"
          maxlength="500"
          show-word-limit
          placeholder="简要说明计划内容"
        />
      </el-form-item>

      <!-- 备件选择/采购（公用子组件） -->
      <!-- <SparePicker
        ref="spareRef"
        v-model:spareType="form.spareType"
        v-model:spares="form.spares"
        v-model:specialItems="form.specialItems"
        :tableHeight="200"
        @need-spare-change="val => (form.needSpare = val)"
      /> -->
      <SparePickerPlus
        ref="spareRef"
        v-model:specialItems="form.specialItems"
        :tableHeight="180"
        selectWidth="360px"
      />
    </el-form>

    <template #footer>
      <div style="display: flex; justify-content: flex-end; gap: 8px">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" :loading="saving" @click="save">
          {{ mode === "create" ? "保存" : "更新" }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch, nextTick } from "vue";
import { ElMessage } from "element-plus";
import {
  createPlan,
  getPlanDetail,
  updatePlan,
  replacePlanSpares,
  replacePlanSpecialSpares,
} from "@/api/sbtz/mtplan";
import SparePickerPlus from "@/components/sbtz/spare/SparePickerPlus.vue";

/** props & emits */
const props = defineProps({
  modelValue: { type: Boolean, default: false },
  mode: { type: String, default: "create" }, // 'create' | 'edit'
  asset: { type: Object, default: () => ({}) }, // 新增时传入
  plan: { type: Object, default: () => ({}) }, // 编辑时传入
});
const emit = defineEmits(["update:modelValue", "success"]);

/** dialog 显隐 */
const visible = ref(false);
watch(
  () => props.modelValue,
  (v) => (visible.value = v),
  { immediate: true }
);
watch(visible, (v) => emit("update:modelValue", v));

/** 表单模型 */
const formRef = ref();
const form = reactive({
  assetId: null,
  title: "",
  planDate: "",
  planHour: 10,
  planContent: "",
  tradeCode: "",
  status: "OPEN",
  specialItems: [],
});

/** 基础校验规则（子表校验交给 SparePicker.validate()） */
const rules = {
  title: [{ required: true, message: "请输入标题", trigger: "blur" }],
  planDate: [{ required: true, message: "请选择计划日期", trigger: "change" }],
  status: [{ required: true, message: "请选择状态", trigger: "change" }],
};

/** 标题与设备名 */
const dialogTitle = computed(() =>
  props.mode === "edit"
    ? `编辑计划 - ${assetName.value}`
    : `新增计划 - ${assetName.value}`
);
const assetName = computed(() =>
  props.mode === "create"
    ? props.asset?.name || "-"
    : props.plan?.assetName || props.asset?.name || "-"
);

/** 工具函数 */
const toInt = (v, def = 0) => {
  const n = Number(v);
  return Number.isFinite(n) ? n : def;
};
function sanitizeCode(input, maxLen = 64) {
  if (input == null) return "";
  let s = String(input).trim().toUpperCase();
  s = s.replace(/[^A-Z0-9\-_]/g, "");
  s = s.replace(/^[-_]+|[-_]+$/g, "");
  if (maxLen > 0 && s.length > maxLen) s = s.slice(0, maxLen);
  return s;
}
/** 如果后端没给 specialItems，而是把特殊备件放在 spares 字段，这里做一次映射以便回显 */
function mapSparesToSpecialItems(spares = []) {
  return (Array.isArray(spares) ? spares : [])
    .map((s) => ({
      name: (s.spareName || s.name || "").trim(),
      code: sanitizeCode(s.spareCode || s.code || ""),
      qty: toInt(s.qty, 1),
      orderDate: toInt(s.spareOrderDate ?? s.orderDate, 1),
    }))
    .filter((r) => r.name && r.code);
}

/** 创建/重置 */
async function resetForCreate() {
  form.assetId = props.asset?.id ?? null;
  form.title = "";
  form.planDate = "";
  (form.planHour = 10), (form.planContent = "");
  form.tradeCode = "";
  form.status = "OPEN";
  form.specialItems = [];
  form.needSpare = 0;
}

/** 编辑回显 */
async function loadForEdit() {
  const id = props.plan?.id;
  if (!id) return;
  const res = await getPlanDetail(id);
  const p = res?.data ?? res;

  form.assetId = p.assetId;
  form.title = p.title || "";
  form.planDate = p.planDate || "";
  form.planHour = p.planHour || 10;
  form.planContent = p.planContent || "";
  form.tradeCode = p.tradeCode || "";
  form.status = p.status || "OPEN";

  const rowsFromSelect = Array.isArray(p.spares)
    ? p.spares.map((s) => ({
        spareId: s.spareId, // 识别为“库内行”
        name: (s.spareName || s.name || "").trim(),
        code: sanitizeCode(s.spareCode || s.code || ""),
        qty: toInt(s.qty, 1),
        orderDate: toInt(s.orderDate, 1),
      }))
    : [];

  // 2) 特殊采购（无 spareId）
  const rowsFromSpecial = Array.isArray(p.specialItems)
    ? p.specialItems.map((r) => ({
        name: (r.name || "").trim(),
        code: sanitizeCode(r.code || ""),
        qty: toInt(r.qty, 1),
        orderDate: toInt(r.orderDate, 1),
      }))
    : [];

  // 3) 合并（并过滤空行）
  form.specialItems = [...rowsFromSelect, ...rowsFromSpecial].filter(
    (x) => x.spareId || (x.name && x.code)
  );
}

/** 打开时加载（根据 create/edit 分支） */
watch(
  () => ({
    open: visible.value,
    mode: props.mode,
    planId: props.plan?.id,
    assetId: props.asset?.id,
  }),
  async ({ open, mode }) => {
    if (!open) return;
    if (mode === "edit") await loadForEdit();
    else await resetForCreate();
  },
  { immediate: false, deep: true }
);

/** 构建提交体（给 create/update） */
function buildPayload() {
  const base = {
    assetId: form.assetId,
    title: form.title,
    planDate: form.planDate,
    planHour: form.planHour,
    planContent: form.planContent,
    tradeCode: form.tradeCode,
    status: form.status,
  };
  console.log(form.specialItems);

  const items = (form.specialItems || [])
    .map((r) => ({
      assetId: form.assetId,
      planDate: form.planDate,
      spareId: r.spareId,
      name: (r.name || "").trim(),
      code: sanitizeCode(r.code || ""),
      qty: toInt(r.qty, 1),
      type: r.type, // 特殊=1
      orderDate: toInt(r.orderDate, 1),
    }))
    .filter((r) => r.name && r.code);

  return { ...base, specialItems: items };
}

 
function buildSparesPayloadForReplace() {
  const list = Array.isArray(form.specialItems) ? form.specialItems : []; 
  const manual = list
    .filter((x) => !x.spareId)
    .map((x) => ({
      assetId: form.assetId,
      planDate: form.planDate,
      planHour: form.planHour,
      name: (x.name || "").trim(),
      code: sanitizeCode(x.code || ""),
      qty: toInt(x.qty, 1),
      orderDate: toInt(x.orderDate, 1),
      type: 1,
    }))
    .filter((x) => x.name && x.code);
  return { manual };
}

/** 保存 */
const spareRef = ref(null);
const saving = ref(false);
async function save() {
  const formOk = await formRef.value?.validate().catch(() => false);
  if (!formOk) return;

  // 拿子组件最新值
  if (spareRef.value?.getValue) {
    const v = spareRef.value.getValue();
    form.specialItems = v.specialItems || [];
  } else {
    await nextTick();
  } 

  saving.value = true;
  try {
    const basePayload = buildPayload();
    let planId = props.plan?.id;

    if (props.mode === "create") {
      await createPlan(basePayload);
       
      // planId = res?.data?.id ?? res?.id;
      ElMessage.success("创建成功");
    } else {
      await updatePlan(planId, basePayload);
      ElMessage.success("更新成功");  

      await replacePlanSpecialSpares(planId, basePayload.specialItems); 
    }

    // 统一替换两类关系
    // const { manual } = buildSparesPayloadForReplace(); 
    // console.log(manual)
    // console.log(basePayload.specialItems);return;    
   
    visible.value = false;
    emit("success");
  } finally {
    saving.value = false;
  }
}
</script>

<style scoped>
/* 让对话框整体按列布局，并限制高度 */
:deep(.dlg-fixed-footer .el-dialog) {
  display: flex;
  flex-direction: column;
  height: 80vh;
  max-height: 90vh;
}

/* 头部加一条底边更清晰 */
:deep(.dlg-fixed-footer .el-dialog__header) {
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f2f5;
}

/* 主体区域占满剩余空间并可滚动 */
:deep(.dlg-fixed-footer .el-dialog__body) {
  flex: 1;
  overflow: auto;
  padding: 16px 24px;
}

/* 页脚固定在底部，保持可见 */
:deep(.dlg-fixed-footer .el-dialog__footer) {
  position: sticky;
  bottom: 0;
  background: #fff;
  border-top: 1px solid #f0f2f5;
  padding: 12px 24px;
  z-index: 2;
}

:deep(.dlg-fixed-footer .el-dialog__footer)::before {
  content: "";
  position: absolute;
  left: 0;
  right: 0;
  top: -8px;
  height: 8px;
  box-shadow: 0 -6px 12px rgba(0, 0, 0, 0.04);
  pointer-events: none;
}
</style>
